<?php
/**
 * Created by PhpStorm.
 * User: zhangwei
 * Date: 2017/7/3
 * Time: 23:24
 */

namespace System\Controller;

use Common\Controller\AdminbaseController;

class AdminRegionController extends AdminbaseController{
	
	
	//区域列表的显示
	public function index(){
		
		$parent_id = I('parent_id',0);
		
		if($parent_id == 0){
			$parent = array('id'=>0,'name'=>"中国省份地区",'level'=>0);
		}else{
			$parent = M('region')->where(array('id'=>$parent_id))->find();
		}
		$names = $this->getParentRegionList($parent_id);
		if(count($names) > 0){
			$names = array_reverse($names);
			$parent_path = implode($names, '>');
		}

		$region = M('region')->where(array('parent_id'=>$parent_id))->select();
		
		$this->assign('parent',$parent);
		$this->assign('parent_path',$parent_path);
		$this->assign('region',$region);
//
		$this->display();
	}
	
	/**
	 * 寻找Region_id的父级字段, $column可自己指定
	 * @param $parent_id
	 * @return array
	 */
	function getParentRegionList($parent_id){
		$names = array();
		
		$region =  M('region')->where(array('id'=>$parent_id))->find();
		array_push($names,$region['name']);
		
		if($region['parent_id'] != 0){
			$nregion = $this->getParentRegionList($region['parent_id']);
			if(!empty($nregion)){
				$names = array_merge($names, $nregion);
			}
		}
		
		return $names;
	}
	
	//区域操作
	public function regionHandle(){
		$data = I('post.');
		$id = I('id');
		$referurl =  isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U("Region/index");
		
		if(empty($id)){
			$data['level'] = $data['level']+1;
			if(empty($data['name'])){
				$this->error("请填写地区名称", $referurl);
			}else{
				$res = M('region')->where("parent_id = ".$data['parent_id']." and name='".$data['name']."'")->find();
				if(empty($res)){
					M('region')->add($data);
					$this->success("操作成功", $referurl);
				}else{
					$this->error("该区域下已有该地区,请不要重复添加", $referurl);
				}
			}
		}else{
			M('region')->where("id=$id or parent_id=$id")->delete();
			$this->success("操作成功", $referurl);
		}
	}
}